import { InfoCircleOutlined } from "@ant-design/icons";
import { Area, Column } from "@ant-design/plots";
import { Col, Progress, Row, Tooltip } from "antd";
import numeral from "numeral";
import useStyles from "../style.style";
import { ChartCard, Field } from "./Charts";
import Trend from "./Trend";
import {searchServers, searchNodes, searchInstances, searchHdfs} from "@/api/masterController";
import { useEffect, useState } from "react";

const topColResponsiveProps = {
    xs: 24,
    sm: 12,
    md: 12,
    lg: 12,
    xl: 6,
    style: {
        marginBottom: 24,
    },
};

// 将数据转换为面积图数据格式
const transformData = (data: API.MrsServers) => {
    if (!data) return [];
    
    // 过滤掉 currentStatus 和 total 字段，并按日期排序
    const dateData = Object.entries(data)
        .filter(([key]) => key !== 'currentSatus' && key !== 'total')
        .sort(([dateA], [dateB]) => {
            // 将日期字符串转换为时间戳进行比较
            const timeA = new Date(dateA).getTime();
            const timeB = new Date(dateB).getTime();
            return timeA - timeB;
        })
        .map(([date, value]) => ({
            x: date,
            y: (value as number) === 0 ? '良好' : '故障'
        }));

    return dateData;
};

const IntroduceRow = ({
                          loading,
                      }: {
    loading: boolean;
}) => {
    const { styles } = useStyles();
    const [serverData, setServerData] = useState<API.MrsServers | null>(null);
    const [nodeData, setNodeData] = useState<API.MrsServers | null>(null);
    const [instanceData, setInstanceData] = useState<API.MrsServers | null>(null);
    const [hdfsData, setHdfsData] = useState<any>(null);
    const [serverVisitData, setServerVisitData] = useState<{ x: string; y: string; }[]>([]);
    const [nodeVisitData, setNodeVisitData] = useState<{ x: string; y: string; }[]>([]);
    const [instanceVisitData, setInstanceVisitData] = useState<{ x: string; y: string; }[]>([]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                // 获取服务器数据
                const serverResponse = await searchServers();
                if (serverResponse.data && Array.isArray(serverResponse.data) && serverResponse.data.length > 0) {
                    const serverInfo = serverResponse.data[0];
                    const transformedServerData = transformData(serverInfo);
                    setServerData(serverInfo);
                    setServerVisitData(transformedServerData);
                }

                // 获取节点数据
                const nodeResponse = await searchNodes();
                if (nodeResponse.data && Array.isArray(nodeResponse.data) && nodeResponse.data.length > 0) {
                    const nodeInfo = nodeResponse.data[0];
                    const transformedNodeData = transformData(nodeInfo);
                    setNodeData(nodeInfo);
                    setNodeVisitData(transformedNodeData);
                }

                // 获取实例数据
                const instanceResponse = await searchInstances();
                if (instanceResponse.data && Array.isArray(instanceResponse.data) && instanceResponse.data.length > 0) {
                    const instanceInfo = instanceResponse.data[0];
                    const transformedInstanceData = transformData(instanceInfo);
                    setInstanceData(instanceInfo);
                    setInstanceVisitData(transformedInstanceData);
                }

                // 获取HDFS数据
                const hdfsResponse = await searchHdfs();
                if (hdfsResponse.data && Array.isArray(hdfsResponse.data)) {
                    setHdfsData(hdfsResponse.data);
                }
            } catch (error) {
                console.error('获取数据失败:', error);
            }
        };

        fetchData();
    }, []);

    // 计算HDFS使用率
    const getHdfsUsagePercent = () => {
        if (!hdfsData) return 0;
        const hdfsSpace = hdfsData.find((item: any) => item.key === 'HDFS Disk Space');
        if (hdfsSpace && hdfsSpace.value) {
            return Math.round((hdfsSpace.value.current / hdfsSpace.value.total) * 100);
        }
        return 0;
    };

    // 获取HDFS文件数
    const getHdfsFileCount = () => {
        if (!hdfsData) return 0;
        const hdfsFile = hdfsData.find((item: any) => item.key === 'HDFS File');
        return hdfsFile ? hdfsFile.value : 0;
    };

    return (
        <Row gutter={24}>
            <Col {...topColResponsiveProps}>
                <ChartCard
                    bordered={false}
                    loading={loading}
                    title="服务故障数"
                    action={
                        <Tooltip title="指标说明">
                            <InfoCircleOutlined />
                        </Tooltip>
                    }
                    total={serverData?.total || 0}
                    footer={
                        <Field
                            label="当前状态"
                            value={
                                <span>
                                    <span
                                        style={{
                                            display: "inline-block",
                                            width: 6,
                                            height: 6,
                                            borderRadius: "50%",
                                            backgroundColor: serverData?.currentSatus === 1 ? "#ff4d4f" : "#52c41a",
                                            marginRight: 8,
                                        }}
                                    />
                                    {serverData?.currentSatus === 1 ? "故障" : "良好"}
                                </span>
                            }
                        />
                    }
                    contentHeight={46}
                >
                    <Area
                        xField="x"
                        yField="y"
                        shapeField="smooth"
                        height={46}
                        axis={false}
                        style={{
                            fill: "linear-gradient(-90deg, white 0%, #975FE4 100%)",
                            fillOpacity: 0.6,
                            width: "100%",
                        }}
                        padding={-20}
                        data={serverVisitData}
                    />
                </ChartCard>
            </Col>

            <Col {...topColResponsiveProps}>
                <ChartCard
                    bordered={false}
                    loading={loading}
                    title="节点故障数"
                    action={
                        <Tooltip title="指标说明">
                            <InfoCircleOutlined />
                        </Tooltip>
                    }
                    total={nodeData?.total || 0}
                    footer={
                        <Field
                            label="当前状态"
                            value={
                                <span>
                                    <span
                                        style={{
                                            display: "inline-block",
                                            width: 6,
                                            height: 6,
                                            borderRadius: "50%",
                                            backgroundColor: nodeData?.currentSatus === 1 ? "#ff4d4f" : "#52c41a",
                                            marginRight: 8,
                                        }}
                                    />
                                    {nodeData?.currentSatus === 1 ? "故障" : "良好"}
                                </span>
                            }
                        />
                    }
                    contentHeight={46}
                >
                    <Area
                        xField="x"
                        yField="y"
                        shapeField="smooth"
                        height={46}
                        axis={false}
                        style={{
                            fill: "linear-gradient(-90deg, white 0%, #975FE4 100%)",
                            fillOpacity: 0.6,
                            width: "100%",
                        }}
                        padding={-20}
                        data={nodeVisitData}
                    />
                </ChartCard>
            </Col>

            <Col {...topColResponsiveProps}>
                <ChartCard
                    bordered={false}
                    loading={loading}
                    title="实例故障数"
                    action={
                        <Tooltip title="指标说明">
                            <InfoCircleOutlined />
                        </Tooltip>
                    }
                    total={instanceData?.total || 0}
                    footer={
                        <Field
                            label="当前状态"
                            value={
                                <span>
                                    <span
                                        style={{
                                            display: "inline-block",
                                            width: 6,
                                            height: 6,
                                            borderRadius: "50%",
                                            backgroundColor: instanceData?.currentSatus === 1 ? "#ff4d4f" : "#52c41a",
                                            marginRight: 8,
                                        }}
                                    />
                                    {instanceData?.currentSatus === 1 ? "故障" : "良好"}
                                </span>
                            }
                        />
                    }
                    contentHeight={46}
                >
                    <Column
                        xField="x"
                        yField="y"
                        padding={-20}
                        axis={false}
                        height={46}
                        data={instanceVisitData}
                        scale={{ x: { paddingInner: 0.4 } }}
                    />
                </ChartCard>
            </Col>

            <Col {...topColResponsiveProps}>
                <ChartCard
                    loading={loading}
                    bordered={false}
                    title="HDFS"
                    action={
                        <Tooltip title="指标说明">
                            <InfoCircleOutlined />
                        </Tooltip>
                    }
                    total={`${getHdfsUsagePercent()}%`}
                    footer={
                        <div
                            style={{
                                whiteSpace: "nowrap",
                                overflow: "hidden",
                            }}
                        >
                            <Trend
                                flag="up"
                                style={{
                                    marginRight: 16,
                                }}
                            >
                                文件数
                                <span className={styles.trendText}>{getHdfsFileCount()}</span>
                            </Trend>
                        </div>
                    }
                    contentHeight={46}
                >
                    <Progress
                        percent={getHdfsUsagePercent()}
                        strokeColor={{ from: "#108ee9", to: "#87d068" }}
                        status="active"
                    />
                </ChartCard>
            </Col>
        </Row>
    );
};

export default IntroduceRow;
